package com.esd.crm.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.esd.crm.Constants;
import com.esd.crm.entity.Filegags;
import com.esd.crm.entity.Project;
import com.esd.crm.service.FilegagsService;
import com.esd.crm.service.ProjectService;
import com.esd.crm.util.KitService;
import com.esd.vo.ReturnResult;



@Controller
@RequestMapping("/filegags")
public class FilegagsController {
	private static Logger logger = Logger.getLogger(FilegagsController.class);
	
	@Autowired
	FilegagsService filegagsService;
	@Autowired
	ProjectService projectService;
	
	@Value(value = "${tempFilePath}")
	private String tempFilePath; // 刚上传文件的缓存目录
	@Value(value = "${fileNameSpliter}")
	private String fileNameSpliter;// 新旧文件名分隔符
	@Value(value = "${resourceFilePath}")
	private String resourceFilePath;// 文件存放路径
	
	@RequestMapping(value = "/singleUpload", method = RequestMethod.GET)
	public ModelAndView uploadGet(HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		// String dir = request.getParameter("dir");
		String projectId = request.getParameter("id");
		// return new ModelAndView("marriage/upload", "dir", dir);
		return new ModelAndView("project/upload", "projectId", projectId);

	}
	
	@RequestMapping(value = "/singleUpload", method = RequestMethod.POST)
	@ResponseBody
	public void upload(HttpSession session, HttpServletRequest request,
			@RequestParam MultipartFile file) {
		String filepath = null;
		String fileName = null;
		// String dir = (String) request.getParameter("dir");
		String projectId = (String) request.getParameter("projectId");
		System.out.println("projectId=!!!!!!!!!!!!!!!!!!!!!!!!!!!!!===>"+projectId);
//		Project project = projectService.findOneProject(projectId);
		List<Project> projects = projectService.findOneProject1(projectId);
		if(projects.size()>1) {
			System.out.println("projects.size()==>"+projects.size());
			int m = 0;
			for (Iterator iterator = projects.iterator(); iterator.hasNext();) {
				Project project = (Project) iterator.next();
				System.out.println(m+"=======:"+project.getId());
				System.out.println(m+"=======:"+project.getProjectname());
				m++;
			}
		}
		Project project = projects.get(0);
		// =====================================
		
		String path = project.getPhotoPath();
		
		if (path.indexOf(".pdf") != -1) {
			
		} else {
			
			filepath = session.getServletContext().getRealPath(
					"photo/"  + path + "/");
			System.out.println("filepath===>"+filepath);
			session.setAttribute("filepath", filepath);
			File f = new File(filepath);
			if (!f.isDirectory()) {
				f.mkdirs();
			}

			// ===========================
			//System.out.printf("filepath:{}", filepath);
			//System.out.printf("size:{}", file.getSize());
			//System.out.printf("type:{}", file.getContentType());

			try {
				String originalFilename = file.getOriginalFilename();
				fileName = KitService.getUUID() + fileNameSpliter + originalFilename;
				if (originalFilename != null) {
					String[] split = originalFilename.split("\\.");
					if (split != null && split.length > 0)
						file.transferTo(new File(filepath + "/"			   
								+fileName));
				}
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		Filegags filegags = new Filegags();
		String originalFilename = file.getOriginalFilename();
		//System.out.println("新文件名====>"+fileName);
		filegags.setOriginalFileName(originalFilename);
		filegags.setFileName(fileName);
		filegags.setBusinessId(projectId);
		filegagsService.addFile(filegags, request, session);
		
	}
	// 通用 单文件异步上传二进制文件, 现将文件保存到${tempFilePath} 目录下, 返回新文件名列表
//	@RequestMapping(value = "/Upload")
//	@ResponseBody
//	public ReturnResult singleUpload_post(@RequestParam("file") MultipartFile[] multipartFiles, HttpServletRequest request)
//			throws Exception {
//		logger.info("*********  上传文件   开始*********");
//		System.out.println("*********  上传文件   开始*********");
//
//		MultipartFile multipartFile;
//		int multipartFilesLength = multipartFiles.length;
//		String[] fileNames = new String[multipartFilesLength];
//		 2- 截取文件名
//		if(multipartFilesLength > 0) {
//			
//			for (int i = 0; i < multipartFilesLength; i++) {
//				multipartFile = multipartFiles[i];
//				String fileName = KitService.getUUID() + fileNameSpliter + multipartFile.getOriginalFilename(); // 新文件名
//				System.out.println("新文件名====>"+fileName);
//				 3- 将文件保存到缓存目录下
//				String basePath = request.getSession().getServletContext().getRealPath(tempFilePath);
//				File resultFile = FileUtils.saveFileFromInputStream(multipartFile.getInputStream(), basePath, fileName);
//				if (!resultFile.exists()) {
//					return ReturnResult.fail(fileName+"上传文件失败, 请重新尝试或联系管理员.");
//				}
//				fileNames[i] = fileName;
//			}
//		}
//		
//		logger.info("*********  上传文件    结束 *********");
//		System.out.println("*********  上传文件    结束 *********");
//		
//		return ReturnResult.success1(fileNames);
//	}
	
	

	
	@RequestMapping(value = "/getImage", method = RequestMethod.GET)
	public ModelAndView imageGet(HttpServletRequest request, HttpSession session) {
		String projectId = request.getParameter("id");
		System.out.printf("userId:{************}", projectId);
		String aaaaa=session.getId();
		System.out.println("aaaaa"+aaaaa);
		Map<String, Object> map = new HashMap<String, Object>();
		List<Project> projects = projectService.findOneProject1(projectId);
		System.out.println("======================="+projects.size());
		List<Filegags> imgs = filegagsService.getFileListByBusinessId(projectId);
		// 如果是图片
		// =====================================
		map.put("src", imgs);
		
		return new ModelAndView("project/imageshow", map);
	}

	
	@RequestMapping(value = "/showImage", method = RequestMethod.GET)
	public void showImage(String id, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		System.out.println("我是showImage");
		
		Filegags img = filegagsService.selectByPrimaryKey(id);
		String name = img.getFileName();
		String fileType = name.split("\\.")[(name.split("\\.").length - 1)];
		String contentType = null;
		if (fileType == "png") {
			contentType = "image/png; charset=utf-8";
		}
		if (fileType == "bmp") {
			contentType = "image/bmp; charset=utf-8";
		}
		if (fileType == "gif") {
			contentType = "image/gif; charset=utf-8";
		}
		if (fileType == "jpg") {
			contentType = "image/jpeg; charset=utf-8";
		}
		if (fileType == "pdf") {
			contentType = "application/pdf; charset=utf-8";
		}
		
			try {
				response.setContentType(contentType);
				response.getOutputStream().write(img.getFile());

				response.getOutputStream().close();
				response.flushBuffer();

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

	}
	
	@RequestMapping(value = "/deletePhoto", method = RequestMethod.POST)
	@ResponseBody
	public ReturnResult deletePhoto(HttpServletRequest request,HttpSession session) {
		String id = request.getParameter("id");
		boolean b1 = filegagsService.deleteByPrimaryKey(id);
		if(b1) {
			return ReturnResult.success();
		}
		if(!b1) {
			System.out.println("数据库图片删除失败");
		}
		return ReturnResult.fail();
	}
	

	
	// 根据文件id返回该文件在资源文件中的网络路径, 以供下载
	@RequestMapping(value = "/download1", method = RequestMethod.POST)
	public void download_post1(@RequestParam(value = "fileId", required = true) String fileId,
			HttpServletRequest request, HttpServletResponse response) {
		System.out.println("*********  下载文件   开始*********");
		logger.info("*********  下载文件   开始*********");
		if (fileId.indexOf(".") > 0) {
			fileId = fileId.substring(0, fileId.indexOf("."));
		}
		Filegags filegags = filegagsService.selectByPrimaryKey(fileId);
		String fileName = filegags.getFileName();
//		String basePath = request.getSession().getServletContext().getRealPath(resourceFilePath);
//		String filePath = basePath + File.separator + fileName;
//		File file = new File(filePath);
//		if(!file.exists() || !file.isFile()) {
//			logger.error("文件不存在");
//			/*ByteArrayInputStream bi = new ByteArrayInputStream(filegags.getFile());*/
//		}else { 
			// 清空response
	        response.reset();
	        String mimeType = request.getSession().getServletContext().getMimeType(fileName);
	        response.setContentType(mimeType);
	        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
	       
	        BufferedInputStream br = null;
	        OutputStream out = null;
	        try {
	        	byte[] bytes = filegags.getFile();
	        	br = new BufferedInputStream(new ByteArrayInputStream(bytes));
				byte[] buf = new byte[1024];
				out = response.getOutputStream();
				int len = 0;
				while ((len = br.read(buf)) > 0){
					out.write(buf, 0, len);
				}
				
			} catch (IOException e) {
				logger.info("下载文件失败，请联系管理员");
				return;
			}finally{
				try {
					br.close();
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
//		}
	}
	
	
	// 根据文件id返回该文件在资源文件中的网络路径, 以供下载
	@RequestMapping(value = "/download", method = RequestMethod.POST)
	public void download_post(@RequestParam(value = "id", required = true) String id,
			HttpServletRequest request, HttpServletResponse response) {
		System.out.println("*********  下载文件   开始*********");
		logger.info("*********  下载文件   开始*********");
		
		List<Filegags> imgs = filegagsService.getFileListByBusinessId(id);
		String packName = id+"@esd.zip";
		String url = request.getSession().getServletContext().getRealPath(resourceFilePath);
		downZIP(imgs,packName,url);
		
		System.out.println("zip包彻底完成");
		System.out.println("url::::"+url);
		System.out.println(File.separator);
		System.out.println("packName::::"+packName);
		
		File file = new File(url + File.separator + packName);
	    if(!file.exists() || !file.isFile()) {
	      logger.error("文件不存在");
	      /*ByteArrayInputStream bi = new ByteArrayInputStream(filegags.getFile());*/
	    }else {
	      // 清空response
	          response.reset();
	          String mimeType = request.getSession().getServletContext().getMimeType(packName);
	          response.setContentType(mimeType);
	          response.setHeader("Content-Disposition", "attachment; filename=" + packName);
	         
	          BufferedInputStream br = null;
	          OutputStream out = null;
	          try {
	            br = new BufferedInputStream(new FileInputStream(file));
	        byte[] buf = new byte[1024];
	        out = response.getOutputStream();
	        int len = 0;
	        while ((len = br.read(buf)) > 0){
	          out.write(buf, 0, len);
	        }
	        
	      } catch (IOException e) {
	        logger.info("下载文件失败，请联系管理员");
	        return;
	      }finally{
	        try {
	          br.close();
	          out.flush();
	          out.close();
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	      }
	    }
		
	}
	
	
	
	/**
	 * 生成zip包
	 * 
	 * @param list
	 * @param packName
	 * @param url
	 * @return
	 */
	public int downZIP(List<Filegags> list, String packName, String url) {
		System.out.println("file================"+url + Constants.SLASH + packName);
		if(!new File(url).exists()) {
			new File(url).mkdirs();
		}
		File zipFile = new File(url + Constants.SLASH + packName);
		if (zipFile.exists()) {
			zipFile.delete();
		}
		try {
			zipFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(zipFile);
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));

			// writeInZIP(list, zos, Constants.WAV,url);
			writeInZIP(list, zos, url);

			zos.close();// 不关闭,最后一个文件写入为0kb
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 1;
	}
	
	
	/**
	 * 读取数据库文件,压入zip文件中
	 * 
	 * @param list
	 * @param zos
	 * @param fileType
	 */
	public void writeInZIP(List<Filegags> list, ZipOutputStream zos,String url) {
		for (Iterator<Filegags> iterator = list.iterator(); iterator.hasNext();) {
			try {
				byte[] bufs = new byte[1024 * 10];
				Filegags filegags = (Filegags) iterator.next();
				String fileName = filegags.getFileName();
//				fileName = fileName.substring(0, fileName.indexOf(Constants.POINT)) + Constants.POINT + fileType;
				// 创建ZIP实体,并添加进压缩包,按原目录结构
				ZipEntry zipEntry = null;
				zipEntry = new ZipEntry(fileName);
				zos.putNextEntry(zipEntry);
				byte[] data = null;
				filegags = filegagsService.selectByPrimaryKey(filegags.getId());
				data = filegags.getFile();
				System.out.println(filegags.getFile()==null);
				if (data != null) {
					InputStream is = new ByteArrayInputStream(data);
					// 读取待压缩的文件并写进压缩包里
					BufferedInputStream bis = new BufferedInputStream(is, 1024);
					int read;
					while ((read = bis.read(bufs)) > 0) {
						zos.write(bufs, 0, read);//
					}
					bis.close();
					is.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
}
